<!--
 * @Description: 
 * @Author: mxy
 * @Date: 2022-12-01 20:47:37
 * @LastEditors: mxy
 * @LastEditTime: 2022-12-01 21:37:35
-->
<template>
  <section class="todoapp">
    <todo-header @add="addData"></todo-header>
    <todo-main
      :list="list2"
      @del="delData"
      @state="changeState"
      @changeAll="all"
    ></todo-main>
    <todo-footer
      :list="list"
      @clear="clearData"
      :flag="flag"
      @taskState="changeTask"
    ></todo-footer>
  </section>
</template>

<script>
import TodoFooter from "./components/TodoFooter.vue";
import TodoHeader from "./components/TodoHeader.vue";
import TodoMain from "./components/TodoMain.vue";
export default {
  components: { TodoHeader, TodoMain, TodoFooter },
  data() {
    return {
      list: JSON.parse(localStorage.getItem("todos")) || [],
      flag: 1,
    };
  },
  methods: {
    delData(id) {
      this.list = this.list.filter((item) => item.id !== id);
    },
    addData(val) {
      this.list.unshift({ id: +new Date(), name: val, isDone: false });
    },
    changeState(id) {
      const res = this.list.find((item) => item.id == id);
      res.isDone = !res.isDone;
    },
    clearData() {
      this.list = this.list.filter((item) => item.isDone == false);
    },
    changeTask(val) {
      this.flag = val;
    },
    all(all) {
      this.list.forEach((item) => (item.isDone = all));
    },
  },
  computed: {
    list2() {
      if (this.flag == 1) {
        return this.list;
      } else if (this.flag == 2) {
        return this.list.filter((item) => item.isDone == false);
      } else {
        return this.list.filter((item) => item.isDone == true);
      }
    },
  },
  watch: {
    list: {
      handler(newList) {
        localStorage.setItem("todos", JSON.stringify(newList));
      },
      deep: true,
    },
  },
};
</script>

<style></style>
